<?php

namespace App\Admin\Controller;

class User extends Authed {
    
    public function index() {
        $do = $this->request->get('do');
        
        $uid = intval($this->request->get('uid'));
        
        if ($do == 'lock') {
            $locked = $this->request->get('locked');
            if ($locked) {
                $result = QF()->User()->unlockOne($uid);
            } else {
                $result = QF()->User()->lockOne($uid);
            }
            
            if ($result) {
                succ();
            } else {
                fail();
            }
        }
        
        $filter_username = urldecode(trim($this->request->get('filter_username')));
        if ($filter_username) {
            $filter_uids = QF()->User()->searchUids($filter_username);
            if ($filter_uids) {
                $filter['uid'] = array('in' => $filter_uids);
            } else {
                $filter['uid'] = -1;
            }
        }
        
        $count = QF()->User()->countAll($filter);
        
        /* 分页 */
        $pager = $this->_createPager($count);
        $length = $pager['length'];
        $start = $pager['offset'];
        $this->assign('pager', $pager);
        
        $rows = QF()->User()->getAll($start, $length, $filter);
        
        $this->assign('rows', $rows);
    }
    
    public function edit() {
        
        $uid = intval($this->request->get('uid'));
        
        if ($this->request->isPost()) {
            
            $data = $this->request->get();
            
            if (!$data['username']) {
                unset($data['username']);
            }
            
            if (!$data['password']) {
                unset($data['password']);
            }
            
            if ($uid) {
                $result = QF()->User()->update($uid, $data);
            } else {
                if (trim($data['username']) == '') {
                    fail('请输入用户名');
                }
                
                $exist_user = QF()->User()->existUser($data['username']);
                if ($exist_user) {
                    fail('该用户名已存在');
                }
                
                if (!trim($data['password'])) {
                    fail('请输入密码');
                }
                
                $result = QF()->User()->add($data);
            }
            
            if ($result) {
                succ('保存成功', '', 2);
            } else {
                fail('保存用户失败');
            }
        }
        
        $this->detail = QF()->User()->get($uid);
        
    }
    
    public function remove() {
        $uid = intval($this->request->get('uid'));
        $result = QF()->User()->remove($uid);
        if ($result) {
            succ();
        } else {
            fail();
        }
    }
}
